<template>
  <div class="link-detail-drawer-overlay" v-if="visible" @click="handleClickOutside">
    <div class="link-detail-drawer" ref="drawerRef" :class="{ 'drawer-visible': drawerVisible }" @click.stop>
      <!-- 标题栏 -->
      <div class="drawer-header">
        <div class="header-title">链接详情</div>
        <button class="header-close" @click="handleClose">
          <i class="fas fa-times"></i>
        </button>
      </div>

      <div class="drawer-content" v-if="linkDetail">
        <!-- 链接基本信息 -->
        <div class="section link-basic-info">
          <div class="section-title">
            <i class="fas fa-info-circle"></i>
            <span>基本信息</span>
          </div>
          <div class="info-grid">
            <div class="info-item">
              <div class="info-label">链接ID</div>
              <div class="info-value">{{ linkDetail.id }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">创建时间</div>
              <div class="info-value">{{ formatDateTime(linkDetail.create_time) }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">过期时间</div>
              <div class="info-value">{{ formatDateTime(linkDetail.expiresAt) }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">状态</div>
              <div class="info-value">
                <span class="status-badge" :class="{ 'active': linkDetail.isActive, 'inactive': !linkDetail.isActive }">
                  {{ linkDetail.isActive ? '启用中' : '已停用' }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 商品信息 -->
        <div class="section product-info">
          <div class="section-title">
            <i class="fas fa-utensils"></i>
            <span>商品信息</span>
          </div>
          <div class="product-card">
            <div class="product-image">
              <img :src="linkDetail.productImage" :alt="linkDetail.productName">
            </div>
            <div class="product-details">
              <div class="product-name">{{ linkDetail.productName }}</div>
              <div class="restaurant-name">{{ linkDetail.restaurantName }}</div>
              <div class="price-info">
                <div class="discount-price">¥{{ formatNumber(linkDetail.discountPrice) }}</div>
                <div class="original-price">¥{{ formatNumber(linkDetail.originalPrice) }}</div>
                <div class="price-off">{{ calculateDiscountPercent(linkDetail.originalPrice, linkDetail.discountPrice)
                }}% OFF</div>
              </div>
              <div class="commission-info">
                <div class="commission-label">佣金:</div>
                <div class="commission-value">¥{{ formatNumber(linkDetail.commission) }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 设置名称 -->
        <div class="section custom-name-section">
          <div class="section-title">
            <i class="fas fa-tag"></i>
            <span>设置名称</span>
          </div>
          <div class="custom-name-card">
            <div class="custom-name">{{ linkDetail.name }}</div>
            <!-- <div class="name-desc">用户在支付页面将看到"您正在帮助{{ linkDetail.name.includes('给') ? linkDetail.name.substring(1) :
              linkDetail.name }}支付外卖"</div> -->
          </div>
        </div>

        <!-- 使用统计 -->
        <div class="section usage-stats">
          <div class="section-title">
            <i class="fas fa-chart-line"></i>
            <span>使用统计</span>
          </div>
          <div class="stats-grid">
            <div class="stat-card">
              <div class="stat-value">{{ linkDetail.visits }}</div>
              <div class="stat-label">访问次数</div>
            </div>
            <div class="stat-card">
              <div class="stat-value">{{ linkDetail.conversions }}</div>
              <div class="stat-label">完成支付</div>
            </div>
            <div class="stat-card">
              <div class="stat-value">{{ linkDetail.conversionRate }}%</div>
              <div class="stat-label">转化率</div>
            </div>
            <div class="stat-card">
              <div class="stat-value">¥{{ formatNumber(linkDetail.totalSales) }}</div>
              <div class="stat-label">总销售额</div>
            </div>
            <div class="stat-card highlight">
              <div class="stat-value">¥{{ formatNumber(linkDetail.totalCommission) }}</div>
              <div class="stat-label">总佣金</div>
            </div>
          </div>
        </div>

        <!-- 链接预览和二维码 -->
        <div class="section link-preview">
          <div class="section-title">
            <i class="fas fa-link"></i>
            <span>链接预览</span>
          </div>
          <div class="preview-area">
            <div class="link-url">
              <div class="url-text">{{ linkDetail.url }}</div>
              <button class="copy-btn" @click="copyLink">
                <i class="fas fa-copy"></i> 复制
              </button>
            </div>
            <div class="qrcode-container">
              <img :src="linkDetail.qrCodeUrl" alt="支付链接二维码">
              <button class="download-btn" @click="downloadQRCode">
                <i class="fas fa-download"></i> 下载二维码
              </button>
            </div>
          </div>
        </div>

        <!-- 链接使用历史 -->
        <div class="section usage-history">
          <div class="section-title">
            <i class="fas fa-history"></i>
            <span>使用历史</span>
          </div>
          <div class="history-table-container">
            <table class="history-table">
              <thead>
                <tr>
                  <th>订单号</th>
                  <th>客户</th>
                  <th>支付方式</th>
                  <th>金额</th>
                  <th>时间</th>
                  <th>地区</th>
                </tr>
              </thead>

              <tbody>
                <tr v-if="linkDetail.historyRecords.length === 0">
                  <td colspan="6" class="empty-records">暂无使用记录</td>
                </tr>
                <tr v-for="record in linkDetail.historyRecords" :key="record.id">
                  <td>{{ record.orderNumber }}</td>
                  <td>{{ record.customer }}</td>
                  <td>{{ record.paymentMethod }}</td>
                  <td>¥{{ formatNumber(record.amount) }}</td>
                  <td>{{ formatDateTime(record.time) }}</td>
                  <td>{{ record.area }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- 加载中状态 -->
      <div v-else-if="loading" class="drawer-loading">
        <div class="loading-spinner">
          <i class="fas fa-spinner fa-spin"></i>
        </div>
        <div class="loading-text">加载链接详情...</div>
      </div>

      <!-- 底部操作按钮 -->
      <div class="drawer-footer" v-if="linkDetail">
        <button class="footer-btn toggle-btn"
          :class="{ 'active': linkDetail.isActive, 'inactive': !linkDetail.isActive }" @click="toggleLinkStatus">
          <i class="fas" :class="linkDetail.isActive ? 'fa-toggle-on' : 'fa-toggle-off'"></i>
          {{ linkDetail.isActive ? '禁用链接' : '启用链接' }}
        </button>
        <button class="footer-btn share-btn" @click="shareLinkDetail">
          <i class="fas fa-share-alt"></i> 分享
        </button>
        <button class="footer-btn delete-btn" @click="deleteLinkDetail">
          <i class="fas fa-trash-alt"></i> 删除
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onMounted, onBeforeUnmount } from 'vue'
import { generateLinkDetailData } from '@/utils/mockData'
import { GetOrderDataListApi } from '@/api/index'

// 定义组件属性
interface Props {
  visible: boolean
  linkId: string
  linkData: object
}

// 定义事件
interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'copy', url: string): void
  (e: 'share', linkDetail: any): void
  (e: 'toggle-status', linkId: string, status: boolean): void
  (e: 'delete', linkId: string): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 内部状态
const drawerRef = ref<HTMLElement | null>(null)
const drawerVisible = ref(false)
const linkDetail = ref<any>(null)
const loading = ref(false)

// 监听visible属性变化
watch(() => props.visible, async (newValue) => {
  if (newValue) {
    // 打开抽屉时，先显示抽屉容器，等待下一个DOM周期后添加动画类
    drawerVisible.value = true

    // 加载数据
    loading.value = true
    try {
      // 模拟API请求延迟
      // await new Promise(resolve => setTimeout(resolve, 600))

      // 获取详情数据
      // linkDetail.value = generateLinkDetailData(props.linkId)

      // const res = await GetOrderDataListApi({ id: props.linkId })


      linkDetail.value = props.linkData

      console.log(789789789, linkDetail.value)


    } catch (error) {
      console.error('获取链接详情失败:', error)
    } finally {
      loading.value = false
    }
  } else {
    // 关闭抽屉时，先移除动画类，动画结束后再隐藏抽屉容器
    drawerVisible.value = false
  }
}, { immediate: true })

// 处理点击抽屉外部
const handleClickOutside = (event: MouseEvent) => {
  if (props.visible &&
    event.target instanceof HTMLElement &&
    !drawerRef.value?.contains(event.target)) {
    handleClose()
  }
}

// 关闭抽屉
const handleClose = () => {
  emit('update:visible', false)
}

// 格式化数字
const formatNumber = (num: number) => {
  return ''
  // return num.toFixed(2)
}

// 计算折扣百分比
const calculateDiscountPercent = (originalPrice: number, discountPrice: number) => {
  return Math.round((1 - discountPrice / originalPrice) * 100)
}

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 复制链接
const copyLink = () => {
  if (linkDetail.value) {
    emit('copy', linkDetail.value.url)
  }
}

// 下载二维码
const downloadQRCode = () => {
  if (linkDetail.value) {
    // 创建一个临时的a标签用于下载
    const link = document.createElement('a')
    link.href = linkDetail.value.qrCodeUrl
    link.download = `qrcode-${linkDetail.value.id}.png`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
}

// 切换链接状态
const toggleLinkStatus = () => {
  if (linkDetail.value) {
    const newStatus = !linkDetail.value.isActive
    linkDetail.value.isActive = newStatus
    linkDetail.value.status = newStatus ? 'active' : 'inactive'
    emit('toggle-status', linkDetail.value.id, newStatus)
  }
}

// 分享链接
const shareLinkDetail = () => {
  if (linkDetail.value) {
    emit('share', linkDetail.value)
  }
}

// 删除链接
const deleteLinkDetail = () => {
  if (linkDetail.value) {
    if (confirm(`确定要删除链接"${linkDetail.value.name}"吗？`)) {
      emit('delete', linkDetail.value.id)
      handleClose()
    }
  }
}

// 添加ESC键关闭抽屉的支持
const handleKeyDown = (e: KeyboardEvent) => {
  if (e.key === 'Escape' && props.visible) {
    handleClose()
  }
}

// 组件挂载时添加事件监听
onMounted(() => {
  window.addEventListener('keydown', handleKeyDown)
})

// 组件卸载前移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeyDown)
})
</script>

<style scoped lang="scss">
// 抽屉遮罩层
.link-detail-drawer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  justify-content: flex-end;
  overflow: hidden;
}

// 抽屉容器
.link-detail-drawer {
  width: 500px;
  max-width: 100%;
  height: 100%;
  background-color: #fff;
  box-shadow: -4px 0 12px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  transform: translateX(100%);
  transition: transform 0.3s ease-in-out;

  &.drawer-visible {
    transform: translateX(0);
  }
}

// 抽屉头部
.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  background-color: #f8f9fa;

  .header-title {
    font-size: 18px;
    font-weight: 600;
    color: #2F3542;
  }

  .header-close {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    background: none;
    border-radius: 4px;
    cursor: pointer;
    color: #6C757D;

    &:hover {
      background-color: #e9ecef;
      color: #2F3542;
    }
  }
}

// 抽屉内容区域
.drawer-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;

  // 区块公共样式
  .section {
    margin-bottom: 24px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    border: 1px solid #eee;

    .section-title {
      display: flex;
      align-items: center;
      font-size: 16px;
      font-weight: 600;
      color: #2F3542;
      padding: 14px 16px;
      border-bottom: 1px solid #eee;

      i {
        margin-right: 8px;
        color: #FF4757;
      }
    }
  }

  // 链接基本信息
  .link-basic-info {
    .info-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 16px;
      padding: 16px;

      .info-item {
        .info-label {
          font-size: 13px;
          color: #6C757D;
          margin-bottom: 4px;
        }

        .info-value {
          font-size: 14px;
          color: #2F3542;

          .status-badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 12px;
            font-weight: 500;

            &.active {
              background-color: #e8f7ef;
              color: #28a745;
            }

            &.inactive {
              background-color: #f1f2f4;
              color: #6c757d;
            }
          }
        }
      }
    }
  }

  // 商品信息
  .product-info {
    .product-card {
      display: flex;
      align-items: center;
      padding: 16px;

      .product-image {
        width: 80px;
        height: 80px;
        border-radius: 8px;
        overflow: hidden;
        margin-right: 16px;
        flex-shrink: 0;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .product-details {
        flex: 1;

        .product-name {
          font-size: 16px;
          font-weight: 600;
          color: #2F3542;
          margin-bottom: 4px;
        }

        .restaurant-name {
          font-size: 13px;
          color: #6C757D;
          margin-bottom: 8px;
        }

        .price-info {
          display: flex;
          align-items: baseline;
          margin-bottom: 6px;

          .discount-price {
            font-size: 18px;
            font-weight: 600;
            color: #FF4757;
            margin-right: 8px;
          }

          .original-price {
            font-size: 14px;
            color: #6C757D;
            text-decoration: line-through;
            margin-right: 8px;
          }

          .price-off {
            font-size: 12px;
            color: #FF4757;
            background-color: #fff0f0;
            padding: 1px 6px;
            border-radius: 10px;
          }
        }

        .commission-info {
          display: flex;
          align-items: center;

          .commission-label {
            font-size: 13px;
            color: #6C757D;
            margin-right: 4px;
          }

          .commission-value {
            font-size: 14px;
            font-weight: 500;
            color: #28a745;
          }
        }
      }
    }
  }

  // 设置名称
  .custom-name-section {
    .custom-name-card {
      padding: 16px;

      .custom-name {
        font-size: 16px;
        font-weight: 500;
        color: #2F3542;
        margin-bottom: 6px;
      }

      .name-desc {
        font-size: 13px;
        color: #6C757D;
        padding: 8px 12px;
        background-color: #f8f9fa;
        border-radius: 4px;
        border-left: 3px solid #FF4757;
      }
    }
  }

  // 使用统计
  .usage-stats {
    .stats-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 12px;
      padding: 16px;

      .stat-card {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 12px;
        background-color: #f8f9fa;
        border-radius: 8px;

        .stat-value {
          font-size: 18px;
          font-weight: 600;
          color: #2F3542;
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: 12px;
          color: #6C757D;
        }

        &.highlight {
          background-color: #fff0f0;

          .stat-value {
            color: #FF4757;
          }
        }
      }

      // 总佣金卡片占用两列宽度
      .highlight {
        grid-column: span 2;
      }
    }
  }

  // 链接预览和二维码
  .link-preview {
    .preview-area {
      padding: 16px;
      display: flex;
      flex-direction: column;
      gap: 16px;

      .link-url {
        display: flex;
        align-items: center;
        background-color: #f8f9fa;
        border: 1px solid #e9ecef;
        border-radius: 6px;
        padding: 8px 12px;

        .url-text {
          flex: 1;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 14px;
          color: #2F3542;
        }

        .copy-btn {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          border: none;
          background-color: #FF4757;
          color: #fff;
          padding: 6px 12px;
          border-radius: 4px;
          font-size: 13px;
          cursor: pointer;
          flex-shrink: 0;
          margin-left: 8px;

          i {
            margin-right: 4px;
          }

          &:hover {
            background-color: darken(#FF4757, 10%);
          }
        }
      }

      .qrcode-container {
        display: flex;
        flex-direction: column;
        align-items: center;

        img {
          width: 180px;
          height: 180px;
          margin-bottom: 12px;
          border: 1px solid #eee;
          border-radius: 4px;
        }

        .download-btn {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          border: none;
          background-color: #2F3542;
          color: #fff;
          padding: 6px 12px;
          border-radius: 4px;
          font-size: 13px;
          cursor: pointer;

          i {
            margin-right: 4px;
          }

          &:hover {
            background-color: darken(#2F3542, 10%);
          }
        }
      }
    }
  }

  // 链接使用历史
  .usage-history {
    .history-table-container {
      padding: 16px;
      overflow-x: auto;

      .history-table {
        width: 100%;
        border-collapse: collapse;

        th,
        td {
          padding: 10px 12px;
          text-align: left;
          border-bottom: 1px solid #eee;
        }

        th {
          font-size: 13px;
          font-weight: 500;
          color: #6C757D;
          background-color: #f8f9fa;
        }

        td {
          font-size: 14px;
          color: #2F3542;
        }

        .empty-records {
          text-align: center;
          color: #6C757D;
          padding: 20px;
        }
      }
    }
  }
}

// 加载状态
.drawer-loading {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #6C757D;

  .loading-spinner {
    font-size: 36px;
    margin-bottom: 16px;
    color: #FF4757;
  }

  .loading-text {
    font-size: 14px;
  }
}

// 抽屉底部
.drawer-footer {
  display: flex;
  padding: 16px;
  border-top: 1px solid #eee;
  background-color: #f8f9fa;

  .footer-btn {
    flex: 1;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 10px 0;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    margin: 0 6px;

    i {
      margin-right: 6px;
    }

    &.toggle-btn {
      &.active {
        background-color: #e9ecef;
        color: #495057;

        &:hover {
          background-color: #dee2e6;
        }
      }

      &.inactive {
        background-color: #28a745;
        color: #fff;

        &:hover {
          background-color: darken(#28a745, 10%);
        }
      }
    }

    &.share-btn {
      background-color: #2F3542;
      color: #fff;

      &:hover {
        background-color: darken(#2F3542, 10%);
      }
    }

    &.delete-btn {
      background-color: #FF4757;
      color: #fff;

      &:hover {
        background-color: darken(#FF4757, 10%);
      }
    }
  }
}

// 响应式调整
@media (max-width: 768px) {
  .link-detail-drawer {
    width: 90%;
  }

  .link-basic-info .info-grid {
    grid-template-columns: 1fr !important;
  }

  .usage-stats .stats-grid {
    grid-template-columns: repeat(2, 1fr) !important;

    .stat-card {
      &.highlight {
        grid-column: span 2;
      }
    }
  }

  .product-info .product-card {
    flex-direction: column;
    align-items: flex-start;

    .product-image {
      margin-right: 0;
      margin-bottom: 12px;
    }
  }

  .drawer-footer {
    padding: 12px;

    .footer-btn {
      padding: 8px 0;
      font-size: 13px;
      margin: 0 4px;
    }
  }
}
</style>
